package moi.savecanalblog;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class WordpressBlogSaver extends BlogSaver {
	public void init(String[] inParams){

		SQLConnection.init(inParams[2], inParams[3], inParams[4], inParams[5]);
		conn=SQLConnection.conn;
		
		messageSaver=new WordPressMessageSaver();
		messageSaver.init(inParams);

	}
	
	public void close(){
		
		messageSaver.close();
	}

	public MessageSaver getMessageSaver(){return messageSaver;}
	
	public void saveLinks(ArrayList<Link> inLinks){
	
		for(Link link:inLinks){
			saveLink(link);
		}	
	}
	
	
	public void saveLink(Link inLink){
		Statement stmt = null;
		String req=null;
		
		System.out.println("Saving "+inLink.name+"...");
		
		try {
			stmt = conn.createStatement();
	    	req="insert into wp_links (link_url,link_name,link_category) values ('"+SQLConnection.sqlEscape(inLink.URL)+"','"+SQLConnection.sqlEscape(inLink.name)+"',"+getOrCreateCategory(inLink.category)+")";
			stmt.executeUpdate(req);
		    
		}catch(Exception e){
			System.err.println("Erreur SQL: "+e.getMessage());
			System.err.println("Requete: "+req);
		} finally {
		    if (stmt != null) {
		        try {
		            stmt.close();
		        } catch (SQLException sqlEx) {  }

		        stmt = null;
		    }
		}
	}
	
	
	protected String getOrCreateCategory(LinkCategory inCat){
		Statement stmt = null;
		ResultSet rs = null;
		String outId=null;
		String req=null;
		
		try {
		    stmt = conn.createStatement();
		    req="SELECT cat_ID FROM wp_linkcategories where cat_name='"+SQLConnection.sqlEscape(inCat.name)+"'";
		    rs = stmt.executeQuery(req);

		    if (rs.next()) {
		    	outId= rs.getString(1);
		    }
		    rs.close();
		    if(outId==null){
		    	req="insert into wp_linkcategories (cat_name) values ('"+SQLConnection.sqlEscape(inCat.name)+"')";
				stmt.executeUpdate(req);
				rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
				if (rs.next()) {
					outId=rs.getString(1);
				}
				rs.close();
		    }
		    
		}catch(Exception e){
			System.err.println("Erreur SQL: "+e.getMessage());
			System.err.println("Requete: "+req);
		} finally {
		    if (rs != null) {
		        try {
		            rs.close();
		        } catch (SQLException sqlEx) {  }

		        rs = null;
		    }

		    if (stmt != null) {
		        try {
		            stmt.close();
		        } catch (SQLException sqlEx) {  }

		        stmt = null;
		    }
		}
		return outId;		
	}
	private static java.sql.Connection conn;
	
	private WordPressMessageSaver messageSaver;
}
